package org.giovanolli.mumi.controller.administration;

import java.util.HashSet;

import org.giovanolli.mumi.controller.AbstractController;
import org.giovanolli.mumi.controller.AbstractModel;
import org.giovanolli.mumi.entities.filter.RoleFilter;
import org.giovanolli.mumi.entities.security.Permission;
import org.giovanolli.mumi.entities.security.Role;
import org.giovanolli.mumi.service.RoleService;
import org.giovanolli.mumi.service.Service;
import org.giovanolli.mumi.view.datamodel.DefaultSelectionDataModelListener;
import org.giovanolli.mumi.view.datamodel.SelectableDataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("roleController")
public class RoleController extends AbstractController<Role> {

	@Autowired
	private RoleService service;

	@Autowired
	private RoleModel model;

	public void init() {
		super.init();
		model.setFilter(new RoleFilter());
	}

	@Override
	protected void bindEntityToModel() {
		Role editedRole = model.getEditedEntity();
		model.setName(editedRole.getName());
		model.setDescription(editedRole.getDescription());

		DefaultSelectionDataModelListener<Permission> selectionListener = new DefaultSelectionDataModelListener<Permission>(new HashSet<Permission>(editedRole.getPermissions()));
		SelectableDataModel<Permission> permissionDataModel = new SelectableDataModel<Permission>(service.getAllPermissions(), selectionListener);
		model.setPermissionsDataModel(permissionDataModel);
		model.setPermissionSelectionListener(selectionListener);
	}

	@Override
	protected void bindModelToEntity() {
		Role editedRole = model.getEditedEntity();
		editedRole.setName(model.getName());
		editedRole.setDescription(model.getDescription());
		editedRole.getPermissions().clear();
		editedRole.getPermissions().addAll(model.getPermissionSelectionListener().getSelectedElements());
	}

	@Override
	protected AbstractModel<Role> getModel() {
		return model;
	}

	@Override
	protected Service<Role> getService() {
		return service;
	}

	protected Class<Role> getEntityClass() {
		return Role.class;
	}
}
